import getemployeemenu from '@/services/accessService';

import { getCurrentCountryCode } from '@/pages/SalaryManage/utils';

import { find, checkAuthCode, getBreadcrumbNameMap, filterMenuData, formatter } from '@/utils/utils';

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

const checkFilterProps = route => ['hideInMenu', 'disabled'].some(item => route[item]);

let filterRoutes = []; // 权限接口数据
let tmpRoutes = []; // 本地权限路由
let flatterMenu = []; // 打平的路由配置
let inited = false;
let fetching = false;

// 设置权限路由
export const setAuthRoutes = async routes => {
    const isLogin = localStorage.getItem('user');
    if (inited || !isLogin) return; // 路由变化onRouteChange是异步的
    fetching = true;
    const menu = await getemployeemenu();
    fetching = false;
    tmpRoutes = []; // 本地权限路由
    filterRoutes = menu.data; // 权限接口数据
    if (menu.code !== 10000) {
        console.error('权限接口错误');
        return;
    }
    inited = true;
    find(routes, filterRoutes, tmpRoutes);
    flatterMenu = getBreadcrumbNameMap(filterMenuData(formatter(tmpRoutes)));
    if (!window.location.search.includes('__auth__=1')) return;
    console.log('权限表格');
    console.table(
        filterRoutes.map(item => {
            const { name, code } = item;
            return { name, code };
        })
    );
};
// 获取权限路由
export const getAuthRoutes = async routes => {
    if (fetching) {
        await sleep(50);
        return getAuthRoutes(routes);
    }

    if (!inited) {
        await setAuthRoutes(routes);
    }
    return {
        filterRoutes,
        tmpRoutes,
        flatterMenu
    };
};
// 清空权限路由
export const clearAuthRoutes = () => {
    tmpRoutes = [];
    filterRoutes = [];
    flatterMenu = [];
    inited = false;
};
// 重置权限路由
export const resetAuthRoutes = async routes => {
    clearAuthRoutes();
    await setAuthRoutes(routes);
};
// 校验权限code
export const checkCode = code => checkAuthCode(code, filterRoutes);

// 获取权限路由
export const getFlatterMenu = () => flatterMenu;

// 根据路由国别筛选
const pathOfCountry = route => !route.countryCode || route.countryCode === getCurrentCountryCode();

export const getActualPath = pathname => {
    const redirectPath = Object.keys(flatterMenu).find(routePath => {
        const route = flatterMenu[routePath];
        if (routePath.includes(pathname) && !checkFilterProps(route) && route.component && pathOfCountry(route)) {
            return true;
        }
        return false;
    });
    return redirectPath;
};

export default {
    setAuthRoutes,
    getAuthRoutes,
    clearAuthRoutes,
    resetAuthRoutes,
    checkCode,
    getFlatterMenu,
    getActualPath
};
